const { add, findtoname, findAll } = require("../model/infoshares")
const moment = require('moment')//格式化时间的插件
const jwt = require("jsonwebtoken");

//添加内容
const addInfo = async function (req, res) {
    //查看 内容 是否传入
    if (!req.body.contents) {
        res.send({ state: false, status: 0, msg: "请传入发布的内容" })
        return;
    }
    //通过token获取用户名
    let authorization = req.body.authorization || req.headers.authorization || req.query.authorization;
    let secrect = "How_are_you";
    // 创建传递数据
    let query = {}
    jwt.verify(authorization, secrect, function (err, decode) {
        // 创建传递数据
        let cTime = moment().format("YYYY/MM/DD HH:mm:ss a")
        query = {
            shareName: decode.name,
            contents: req.body.contents,
            cTime,
            imgSrc: req.body.imgSrc||""
        }
    })
    let result = await add(query)
    if(result){
        res.send({ state: true, status: 1, msg: "内容添加成功" })
    }else{
        res.send({ state: false, status: 0, msg: "内容添加失败" })
    }
}

// 查找分享信息  可传递id   可分页
const getAllshare = async (req, res) => {
    let page = req.body['page'] || 1;
    let count = req.body['count'] || 10;
    let counts = {
        skip: (page - 1) * count,
        limit: count - 0
    }
    let query = {}
    if (req.body.shareName) { query.shareName=req.body.shareName}
    let result = await findtoname(query, counts)
    if (result) {
        res.send({ status: 1, state: true, msg: "查询成功", data: result })
    } else {
        res.send({ status: 0, state: false, msg: "查询失败" })
    }
}

// 查询所有分享信息，可查询单个用户的所有记录
const getAllshareorfromname = async (req, res) => {
    let query = {}
    if (req.body.name) { query.shareName = req.body.name}
    console.log(query,"------");
    
    let result = await findAll(query)
    if (result) {
        res.send({ status: 1, state: true, msg: "查询成功", data: result })
    } else {
        res.send({ status: 0, state: false, msg: "查询失败" })
    }
}


module.exports = {
    addInfo, getAllshare, getAllshareorfromname
}